package com.ek.util;

public class BitwiseUtils {

    /**
     * @param key
     */
    public void printBits(byte[] key) {
        for (int i = 0; i < key.length; i++) {
            printBits(key[i], 7);
        }
        System.out.println();
    }

    /**
     * @param b
     * @param index
     */
    public void printBits(byte b, int index) {
        if (index != -1) {
            System.out.print("" + (b >>> index & 0x01));
            printBits(b, --index);
        }
    }

    /**
     * @param keyA
     * @param keyB
     * @return
     */
    public int commonPrefix(byte[] keyA, byte[] keyB) {
        int allCount = 0;
        int count = 8;
        for (int i = 0; i < keyA.length && count == 8; i++) {
            count = commonPrefix(keyA[i], keyB[i], 7, 0);
            allCount += count;
        }
        return allCount;
    }

    /**
     * @param keyA
     * @param keyB
     * @param index
     * @param count
     * @return
     */
    private int commonPrefix(byte keyA, byte keyB, int index, int count) {
        if (keyA >>> index == keyB >>> index && index != -1) {
            return commonPrefix(keyA, keyB, --index, ++count);
        } else {
            return count;
        }
    }

}
